package com.fds.demo.alipay.config;

import com.alipay.api.AlipayApiException;
import com.fds.demo.alipay.utils.AliPayUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author: fds
 * @date: 2019/11/1
 * @description: 通知回调
 */
public class AliPayNotify {

    /**
     * 返回标志判断是否成功.
     * @param request 请求头
     * @param aliPayConf 阿里支付配置
     * @param aliPayNotifyResult 成功失败回调
     * @return String
     * @throws AlipayApiException
     */
    public String validSuccess(final HttpServletRequest request, final AliPayConf aliPayConf,
                               final AliPayNotifyResult aliPayNotifyResult) throws AlipayApiException {
        Map<String, String> result = AliPayUtils.toMap(request);
        if (AliPayUtils.verifyResult(result, aliPayConf.getAliPayPublicCertPath())) {
            if ("TRADE_SUCCESS".equals(result.get("trade_status"))) {
                return aliPayNotifyResult.paySuccess(result);
            } else if ("TRADE_FINISHED".equals(result.get("trade_status"))) {
                aliPayNotifyResult.paySuccess(result);
                return "success";
            } else {
                aliPayNotifyResult.payFail(result);
                return "success";
            }
        } else {
            aliPayNotifyResult.verifyFail(result);
            return "success";
        }
    }
}
